<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style type="text/css">
	#div1{width:100px; height: 100px; background-color: red;position: absolute;}
	</style>
	<script type="text/javascript">
	window.onload = function (){
		var oDiv = document.getElementById('div1');

		/*
			onmousedown : 选择元素
			onmousemove : 拖动元素
			onmouseup   : 释放元素
		*/

		oDiv.onmousedown = function (ev){
			var ev = ev || event;

			var disX = ev.clientX - this.offsetLeft;
			var disY = ev.clientY - this.offsetTop;

			document.onmousemove = function (ev){					//不用oDiv的原因：当鼠标移动太快离开oDiv时停止
				var ev = ev || event;

			 	oDiv.style.left = ev.clientX -disX + 'px';
			 	oDiv.style.top = ev.clientY - disY + 'px';
			 }

			 document.onmouseup = function (){						//不用oDiv的原因：如果有一个元素的层级z-index高于这个div抬起鼠标仍可移动

			 	document.onmouseup = document.onmousemove = null;		//最好就是把这两个函数内部的函数up和move都清掉
			 }
		}
	}
	</script>
</head>
<body>
	<div id="div1"></div>
</body>
</html>